package com.shensi.adminCollect.controller.station;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.shensi.common.core.controller.BaseController;
import com.shensi.common.core.domain.AjaxResult;
import com.shensi.common.core.page.TableDataInfo;
import com.shensi.common.redis.service.RedisCache;
import com.shensi.adminCollect.common.exception.CustomException;
import com.shensi.adminCollect.domain.station.Enterprise;
import com.shensi.adminCollect.domain.station.Grade;
import com.shensi.adminCollect.domain.station.Station;
import com.shensi.adminCollect.domain.station.dto.UploadWxImgDto;
import com.shensi.adminCollect.domain.station.img;
import com.shensi.adminCollect.service.station.GzhMenuService;
import com.shensi.adminCollect.service.station.IEnterpriseService;
import com.shensi.adminCollect.service.station.IGradeService;
import com.shensi.adminCollect.service.station.IStationService;
import com.shensi.adminCollect.service.system.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.sql.SQLException;
import java.util.*;

import com.shensi.common.core.domain.model.LoginUser;
import com.shensi.common.core.utils.SecurityUtils;
import com.shensi.common.core.domain.entity.SysUser;
/**
 * 油站信息Controller
 *
 * @author qujia
 * @date 2020-12-08
 */
@Api(value = "油企信息管理页面接口",description = "油企信息管理页面接口")
@RestController
@RequestMapping("/enterprise/info")
public class EnterpriseController extends BaseController
{
    @Autowired
    private IEnterpriseService enterpriseService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IGradeService gradeService;
    @Autowired
    private IStationService stationService;

    @Autowired
    private RedisCache redisCache;

    @Resource
    private GzhMenuService gzhMenuService;


    /**
     * 查询油企名，油站名
     */
    @GetMapping("/getEnterpriseandStation")
    @ApiOperation("查询油企名，油站名")
    public AjaxResult getEnterpriseandStation() {
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            Enterprise enterprise = enterpriseService.selectEnterpriseById(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);

            // 构造返回数据
            Map<String, Object> result = new HashMap<>();
            // 获取油企名
            String enterpriseName = enterprise.getEnterpriseName(); // 假设您可以从某个地方获取油企名
            result.put("enterpriseName", enterpriseName);
            // 获取油站列表
            List<String> stationList = new ArrayList<>();
            for (Station ss : stations) {
                stationList.add(ss.getStationName() + "");
            }
            result.put("stationList", stationList);

            return AjaxResult.success(result);
        } else if ("2".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            Enterprise enterprise = enterpriseService.selectEnterpriseById(current.getUser().getEnterpriseId());

            // 构造返回数据
            Map<String, Object> result = new HashMap<>();
            // 获取油企名
            String enterpriseName = enterprise.getEnterpriseName(); // 假设您可以从某个地方获取油企名
            result.put("enterpriseName", enterpriseName);
            // 获取油站列表
            List<String> stationList = new ArrayList<>();
            stationList.add(current.getUser().getStationName());
            result.put("stationList", stationList);

            return AjaxResult.success(result);
        } else {
            // 处理其他情况
            Map<String, Object> result = new HashMap<>();
            result.put("enterpriseName", "");
            result.put("stationList", "");
            return AjaxResult.success(result);
        }
    }

    /**
     * 查询油站信息列表
     */
    @GetMapping("/transactionEnterpriseList")
    @ApiOperation("查询分账油企信息列表")
    public TableDataInfo transactionEnterpriseList(@Valid Enterprise enterprise)
    {
        List<Enterprise> enterpriseList = enterpriseService.transactionEnterpriseList(enterprise);
        return getDataTable(enterpriseList);
    }
    /**
     * 查询油站信息列表
     */
    @GetMapping("/list")
    @ApiOperation("查询油站信息列表")
    public TableDataInfo list(@Valid Enterprise enterprise)
    {
        startPage();
        enterprise.setDeleteStatus("0");
        //将地址和图片转为string
        String regionData1="";
        String licenseImg="";
        String ImgName="";
        if (enterprise.getRegionDataList() !=null&&enterprise.getRegionDataList().length>0) {
            for (String regionData : enterprise.getRegionDataList()) {
                if ("".equals(regionData1)) {
                    regionData1 += regionData;
                } else {
                    regionData1 += "," + regionData;
                }
            }
            if (!"".equals(regionData1)) {
                enterprise.setRegionData(regionData1);
            }
        }
        if (enterprise.getImgFileList()!=null&&enterprise.getImgFileList().size()>0) {
            for (img img1 : enterprise.getImgFileList()) {
                if ("".equals(licenseImg)) {
                    licenseImg += img1.getUrl();
                    ImgName +=img1.getName();
                } else {
                    licenseImg +="," +img1.getUrl();
                    ImgName +=","+img1.getName();
                }
            }

            if ("".equals(licenseImg)) {
                enterprise.setLicenseImg(licenseImg);
                enterprise.setLicenseName(ImgName);
            }
        }
        List<Enterprise> enterpriseList = enterpriseService.selectEnterpriseList(enterprise);
        //List<Enterprise> enterpriseList1=new ArrayList<>();

        for(int mm=0;mm<enterpriseList.size();mm++){

            if(enterpriseList.get(mm).getRegionData()!=null){
                enterpriseList.get(mm).setRegionDataList(enterpriseList.get(mm).getRegionData().split(","));
            }
            List<img>  imgs=new ArrayList<>();
            if(enterpriseList.get(mm).getLicenseImg()!=null){
                String[] message= enterpriseList.get(mm).getLicenseImg().split(",");
               // String[] name= enterprise1.getLicenseName().split(",");
                /*for(int i=0;i<name.length;i++){
                    img img2=new img();
                    img2.setName(name[i]);
                    img2.setUrl(message[i]);
                    imgs.add(img2);
                }*/
            }
            enterpriseList.get(mm).setImgFileList(imgs);
        }

        return getDataTable(enterpriseList);
    }

    /**
     * 逻辑删除
     */
    @PostMapping(value = "/deleteEnterprise")
    public AjaxResult deleteEnterprise(@RequestBody Enterprise enterprise)
    {
        int i=0;
        LoginUser currentUser = SecurityUtils.getLoginUser();
        //防止修改其他参数
        Enterprise enterprise1=new Enterprise();
        enterprise1.setEnterpriseId(enterprise.getEnterpriseId());
        enterprise1.setDeleteDate(new Date());
        enterprise1.setDeleteStatus("1");
        enterprise1.setDeleteUser(currentUser.getUser().getUserId());

        try {
          i= enterpriseService.updateEnterprise(enterprise1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(i);
    }



    /**
     * 创建微信卡卷
     */
    @PostMapping(value = "/createCardEnterprise")
    public AjaxResult createCardEnterprise(@RequestBody Enterprise enterprise)
    {
//        if(enterprise.getEnterpriseId()!=null) {
//            Enterprise enterprise1 = enterpriseService.selectEnterpriseById(enterprise.getEnterpriseId());
//            if (enterprise1.getCardId()!=null) {
//               return AjaxResult.error("当前油企以获取卡卷，不可重新获取");
//            }
//        }
        return enterpriseService.createCardEnterprise(enterprise);
    }



    /**
     * 修改优惠卷开启状态的标识
     */
    @ApiOperation("根据登录人，对优惠卷开启状态进行修改")
    @ApiImplicitParam(name = "updateCouponEnabledFlag", value = "修改优惠卷开启开启状态", dataType = "String")
    @PostMapping(value = "/updateCouponEnabledFlag")
    public AjaxResult updateCouponEnabledFlag(@RequestBody String flag)
    {
        int i=0;
        LoginUser currentUser = SecurityUtils.getLoginUser();
        //防止修改其他参数
        Enterprise enterprise1=new Enterprise();
        enterprise1.setEnterpriseId(currentUser.getUser().getEnterpriseId());
        enterprise1.setCouponEnabledFlag(flag);
        try {
            i=enterpriseService.updateEnterprise(enterprise1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(i);
    }

    /**
     * 新增油企
     */

    @PostMapping
    public AjaxResult add(@RequestBody Enterprise enterprise) throws  Exception
    {

         int i=0;
         String [] codevalue={"1","2","3","4","5"};
        String [] name={"普卡","白银","黄金","钻石","黑卡"};
        Long [] growvalue={0L, 900000000L,900000001L,900000002L,900000003L};
        String regionData1="";
        String licenseImg="";
        String ImgName="";
        if (enterprise.getRegionDataList()!=null&&enterprise.getRegionDataList().length>0) {
            for (String regionData : enterprise.getRegionDataList()) {
                if ("".equals(regionData1)) {
                    regionData1 += regionData;
                } else {
                    regionData1 += "," + regionData;
                }
            }
            if(!"".equals(regionData1)){
                enterprise.setRegionData(regionData1);
            }
        }
        if (enterprise.getImgFileList()!=null&&enterprise.getImgFileList().size()>0) {
            for (img img1 : enterprise.getImgFileList()) {
                if ("".equals(licenseImg)) {
                    licenseImg += img1.getUrl();
                    ImgName +=img1.getName();
                } else {
                    licenseImg +="," +img1.getUrl();
                    ImgName +=","+img1.getName();
                }
            }

            if ("".equals(licenseImg)) {
                enterprise.setLicenseImg(licenseImg);
                enterprise.setLicenseName(ImgName);
            }
        }
        Calendar cal = Calendar.getInstance();
        Random random=new Random();
        String result1 = "";
        for (int m = 0; m < 4; m++) {
            result1 += random.nextInt(10);
        }
        int year = cal .get(Calendar.YEAR);
        int month = cal .get(Calendar.MONTH) + 1;
        int yearcount=year-2000;
        String code="C"+yearcount+month+"0001"+result1;
        enterprise.setEnterpeiseCode(code);
        i= enterpriseService.insertEnterprise(enterprise);
        //初始化小程序功能配置
        enterpriseService.initgzhFunction(enterprise.getEnterpriseId());
        if(i<=0){
            return toAjax(0);
        }
        Long[] roles={Long.parseLong(18+"")};
        Enterprise enterprise1=enterpriseService.selectEnterpriseList(enterprise).get(0);
        SysUser sysUser=new SysUser();
        sysUser.setDeptId((long) 100);
        sysUser.setUserName(code);
        sysUser.setNickName(enterprise.getEnterpriseName());
        sysUser.setUserLevel("1");
        sysUser.setPhonenumber(enterprise.getPhone());
        sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
        sysUser.setEnterpriseId(enterprise1.getEnterpriseId());
        sysUser.setRoleIds(roles);
        i=sysUserService.insertUser(sysUser);
        if(i<=0){
           throw new  SQLException("插入用户失败");
        }
       for(int m=0;m<5;m++){
           Grade grade=new Grade();
           grade.setEnterpriseId(enterprise1.getEnterpriseId());
           grade.setGradeGrowValue(growvalue[m]);
           if (Objects.isNull(enterprise.getGzhAppId())){
               LoginUser current=SecurityUtils.getLoginUser();
               grade.setCreateUser(current.getUser().getUserId());
           }else {
               grade.setCreateUser(enterprise.getCreateUser());
           }
           grade.setCreateTime(new Date());
           grade.setGradeName(name[m]);
           grade.setGradeCode(codevalue[m]);
          i= gradeService.insertGrade(grade);
       }
        return toAjax(i);
    }


    /**
     * 获取油站信息详细信息
     */
    @GetMapping(value = "/{enterpriseId}")
    public AjaxResult getInfo(@PathVariable("enterpriseId") Long enterpriseId)
    {
        Enterprise enterprise=enterpriseService.selectEnterpriseById(enterpriseId);
        if(enterprise.getRegionData()!=null){
            enterprise.setRegionDataList(enterprise.getRegionData().split(","));
        }
        if(enterprise.getLicenseImg()!=null){
            List<img>  imgs=new ArrayList<>();
            if(enterprise.getLicenseImg()!=null){
                String[] message= enterprise.getLicenseImg().split(",");
                String[] name= enterprise.getLicenseImg().split(",");

                for(int i=0;i<name.length;i++){
                    img img2=new img();
                    img2.setName(name[i]);
                    img2.setUrl(message[i]);
                    imgs.add(img2);
                }
            }
            enterprise.setImgFileList(imgs);
        }
        return AjaxResult.success(enterprise);
    }

    /**
     * 修改油站信息
     */
    @PutMapping
    @ApiOperation("----")
    public AjaxResult edit(@RequestBody Enterprise enterprise)
    {
        int i=0;
        String regionData1="";
        String licenseImg="";
        String ImgName="";

        if (enterprise.getRegionDataList()!=null&&enterprise.getRegionDataList().length>0) {
            for (String regionData : enterprise.getRegionDataList()) {
                if ("".equals(regionData1)) {
                    regionData1 += regionData;
                } else {
                    regionData1 += "," + regionData;
                }
            }
            if(!"".equals(regionData1)){
                enterprise.setRegionData(regionData1);
            }
        }
        if (enterprise.getImgFileList()!=null&&enterprise.getImgFileList().size()>0) {
            for (img img1 : enterprise.getImgFileList()) {
                if ("".equals(licenseImg)) {
                    licenseImg += img1.getUrl();
                    ImgName +=img1.getName();
                } else {
                    licenseImg +="," +img1.getUrl();
                    ImgName +=","+img1.getName();
                }
            }

            if ("".equals(licenseImg)) {
                enterprise.setLicenseImg(licenseImg);
                enterprise.setLicenseName(ImgName);
            }
        }
        try {
            redisCache.deleteObject("EnterpriseServiceImpl_selectEnterpriseInfo::" + "e_" +enterprise.getEnterpriseId() );
           i=enterpriseService.updateEnterprise(enterprise);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        return toAjax(i);
    }


    /**
     * 查询油企的选项
     */
    @GetMapping("/listOption")
    public TableDataInfo listOption(Enterprise enterprise)
    {
        LoginUser current=SecurityUtils.getLoginUser();
        startPage();
        enterprise.setDeleteStatus("0");
        List<Enterprise> enterpriseList=new ArrayList<>();
        if(current.getUser().getEnterpriseId()!=null){
            enterpriseList.add(enterpriseService.selectEnterpriseById(current.getUser().getEnterpriseId()));

        }else {
            enterpriseList = enterpriseService.selectEnterpriseList(enterprise);
        }
        return getDataTable(enterpriseList);
    }

    /**
     * 查询油企是否有appid
     */
    @ApiOperation(value = "查询油企是否有appid")
    @PostMapping("/selectEnterpriseAppid")
    @ApiImplicitParam(name = "enterpriseId", value = "油企id", dataType = "Long", example = "123")
    public AjaxResult selectEnterpriseAppid(Long enterpriseId){
    	Enterprise enterprise=enterpriseService.selectEnterpriseById(enterpriseId);
    	boolean enterpriseBoolean=true;
    	if(enterprise==null || StringUtils.isEmpty(enterprise.getAppId()) ) {
    		enterpriseBoolean=false;
    	}
        return AjaxResult.success("成功",enterpriseBoolean);
    }

    @PostMapping("/updateMenuBar")
    @ApiOperation(value = "自定义公众号菜单")
    public AjaxResult updateMenuBar(@RequestBody String requestBody) throws Exception {
        LoginUser current=SecurityUtils.getLoginUser();
        if(!"1".equals(current.getUser().getUserLevel())){
            throw new CustomException("请使用油企账号修改");
        }
        Long enterpriseId = current.getUser().getEnterpriseId();

        logger.info("修改公众号菜单栏入参【{}】",requestBody);
        JSONObject jsonObject;
        try {
             jsonObject = JSONObject.parseObject(requestBody);
        }catch (Exception e){
            throw new CustomException("参数格式错误");
        }

        return gzhMenuService.updateGzhMenu(enterpriseId, jsonObject);
    }

    @GetMapping("/getMenuBar")
    @ApiOperation(value = "获取自定义公众号菜单")
    public AjaxResult getMenuBar() throws Exception {
        LoginUser current=SecurityUtils.getLoginUser();
        if(!"1".equals(current.getUser().getUserLevel())){
            throw new CustomException("请使用油企账号修改");
        }
        return gzhMenuService.getGzhMenu(current.getUser().getEnterpriseId());

    }

    @GetMapping("/getGzhStatus")
    @ApiOperation(value = "获取公众号授权状态")
    public AjaxResult gzhStatus(@RequestParam String enterpriseId){
        return gzhMenuService.getGzhStatus(enterpriseId);

    }

    /**
     * 修改卡券信息
     * */
    @PostMapping("/updateCardInfo")
    @ApiOperation(value = "自定义会员")
    public AjaxResult updateCardInfo(@RequestBody String requestBody){
        logger.info("自定义会员卡的参数requestBody:【{}】",requestBody);
        LoginUser current=SecurityUtils.getLoginUser();
        if(!"1".equals(current.getUser().getUserLevel())){
            throw new CustomException("请使用油企账号修改");
        }
        Long enterpriseId = current.getUser().getEnterpriseId();
        return gzhMenuService.updateCardInfo(enterpriseId, requestBody);
    }

    @GetMapping("/getCardInfo")
    @ApiOperation(value = "获取会员卡信息")
    public AjaxResult getCardInfo(){
        LoginUser current=SecurityUtils.getLoginUser();
        if(!"1".equals(current.getUser().getUserLevel())){
            throw new CustomException("请使用油企账号修改");
        }
        Long enterpriseId = current.getUser().getEnterpriseId();
        return gzhMenuService.getCardInfo(enterpriseId);
    }

    @GetMapping("/getLinkedMiniProgram")
    @ApiOperation(value = "获取公众号绑定的小程序信息")
    public AjaxResult getLinkedMiniProgram(){
        LoginUser current=SecurityUtils.getLoginUser();
        if(!"1".equals(current.getUser().getUserLevel())){
            throw new CustomException("请使用油企账号修改");
        }
        Long enterpriseId = current.getUser().getEnterpriseId();
        return gzhMenuService.getLinkedMiniProgram(enterpriseId);

    }

    @PostMapping("/uploadImgToWx")
    @ApiOperation(value = "上传图片到微信")
    public AjaxResult uploadImgToWx(@RequestBody UploadWxImgDto uploadWxImgDto){
        LoginUser current=SecurityUtils.getLoginUser();
        if(!"1".equals(current.getUser().getUserLevel())){
            throw new CustomException("请使用油企账号修改");
        }
        Long enterpriseId = current.getUser().getEnterpriseId();
        String responseBody = gzhMenuService.uploadImgToWx(enterpriseId, uploadWxImgDto.getImgUrl());

        return AjaxResult.success("上传成功", responseBody);
    }

    @GetMapping("/backgroundPicUrl")
    @ApiOperation(value = "公众号会员卡封面背景图片地址")
    public AjaxResult saveBackgroundPicUrl(@RequestParam("backgroundPicUrl") String backgroundPicUrl){
        LoginUser current=SecurityUtils.getLoginUser();
        if(!"1".equals(current.getUser().getUserLevel())){
            throw new CustomException("请使用油企账号修改");
        }
        Long enterpriseId = current.getUser().getEnterpriseId();
        Enterprise enterprise = new Enterprise();
        enterprise.setBackgroundPicUrl(backgroundPicUrl);
        enterprise.setEnterpriseId(enterpriseId);
        int i = enterpriseService.updateEnterpriseCardLogo(enterprise);
        if(i <= 0){
            return AjaxResult.error("上线图片地址失败");
        }
        return AjaxResult.success("上线图片地址成功");
    }

    // 修改是否开启每升立减活动信息展示
    @GetMapping("/show/activity")
    @ApiOperation(value = "修改是否开启每升立减活动信息展示")
    public AjaxResult showActivity(@RequestParam("isShow") Integer isShow){
        LoginUser current=SecurityUtils.getLoginUser();
        if(!"1".equals(current.getUser().getUserLevel())){
            throw new CustomException("请使用油企账号修改");
        }
        Long enterpriseId = current.getUser().getEnterpriseId();
        Enterprise enterprise = new Enterprise();
        enterprise.setEnterpriseId(enterpriseId);
        enterprise.setIsShow(isShow);
        int i = enterpriseService.updateEnterpriseCardLogo(enterprise);
        if(i <= 0){
            return AjaxResult.error("修改失败");
        }
        return AjaxResult.success("修改成功");
    }

    // 查看是否开启每升立减活动信息展示
    @GetMapping("/get/show")
    @ApiOperation(value = "查看是否开启每升立减活动信息展示")
    public AjaxResult getShow(){
        LoginUser current=SecurityUtils.getLoginUser();
        if(!"1".equals(current.getUser().getUserLevel())){
            throw new CustomException("请使用油企账号修改");
        }
        Long enterpriseId = current.getUser().getEnterpriseId();
        Enterprise enterprise = enterpriseService.selectEnterpriseById(enterpriseId);
        return AjaxResult.success(enterprise);
    }
}
